package com.wxq.workpad.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.wxq.workpad.utils.ApplicationUtils
import com.wxq.workpad.utils.log.LogUtils
import com.wxq.workpad.widget.LoadingUtils
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

open abstract class BaseFragment<VB : ViewBinding> : Fragment(),
    RealShow {
    lateinit var binding: VB
    protected var mContext: Context? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = activity
    }


    // 当前已经可见
    var isRealShow=false
    var hasLazyLoad=false
    var onActivityCreatedHasFinish=false

    override fun realShow() {
        if (isRealShow) {
            return
        }
        if (onActivityCreatedHasFinish) {
            if (!hasLazyLoad){
                lazyLoad()
                hasLazyLoad=true
            }
        }
        isRealShow=true

    }


    override fun onStart() {
        super.onStart()

    }

    // lazy laod
   open fun lazyLoad(){

    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return getRootView()
    }


    private fun getRootView():View {
        val superclass: Type = javaClass.genericSuperclass
        val aClass = (superclass as ParameterizedType).getActualTypeArguments().get(0) as Class<*>
        val method: Method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        binding = method.invoke(null, layoutInflater) as VB
        return (binding.root)
    }



    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        LogUtils.e("onActivityCreated")
        init()
        onActivityCreatedHasFinish=true
        if (isRealShow) {
            if (!hasLazyLoad){
                lazyLoad()
                hasLazyLoad=true
            }
        }


    }

    protected abstract fun init()

    fun showToast(it:String){
        Toast.makeText(ApplicationUtils.getTopActivity(), it, Toast.LENGTH_SHORT).show()
    }



    private val dialogUtils by lazy {
        LoadingUtils(mContext!!)
    }
    /**
     * 加载提示框
     */
    fun showLoading() {
        dialogUtils.showLoading("加载中")
    }

    /**
     * 关闭提示框
     */
    fun dismissLoading() {
        dialogUtils.dismissLoading()
    }

}